package com.ushine.web.base;

import com.ushine.web.base.utils.FileUtils;
import com.ushine.web.utils.DateTimeUtils;
import com.ushine.web.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.service.spi.ServiceException;
import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @Author: yls
 * @Date 2022/3/18 16:00
 * @Description: 单元测试记录
 * @Version 1.0
 **/
@Component
@Slf4j
public class BestTestLog {


    /**
     * 测试用例：文件记录
     */
    private static final String TEST_LOG = FileUtils.getTestResourcePath()+"\\log";

    /**
     * 功能描述:
     * 〈 记录测试用例 〉
     *
     * @param tempPath 文件路径
     * @param params 参数
     * @param code 响应状态
     * @param result  响应结果
     * @return : void
     * @author : yls
     * @date : 2022/3/18 15:09
     */
    public void writeTestLog(String tempPath, String params, Integer code, String result) {
        String path = TEST_LOG +File.separator + DateUtils.getNowYearMonthDay().toString() + File.separator + tempPath;

        FileWriter fileWriter = null;
        BufferedWriter bufferedWriter = null;
        try {
            File file = new File(path);
            if (!file.getParentFile().exists()) {
                boolean mkdirs = file.getParentFile().mkdirs();
                if (!mkdirs) {
                    throw new ServiceException("文件夹创建失败！");
                }
            }
            if (!file.exists()) {
                boolean newFile = file.createNewFile();
                if (!newFile) {
                    throw new ServiceException("文件创建失败！");
                }
            }
            fileWriter = new FileWriter(path, true);
            bufferedWriter = new BufferedWriter(fileWriter);
            // 写入文件
            bufferedWriter.write("执行时间："+ DateTimeUtils.getNowTime());
            bufferedWriter.newLine();
            bufferedWriter.write("tempPath："+tempPath);
            bufferedWriter.newLine();
            bufferedWriter.write("params："+params);
            bufferedWriter.newLine();
            bufferedWriter.write("code："+code);
            bufferedWriter.newLine();
            bufferedWriter.write("result："+result);
            bufferedWriter.newLine();
            bufferedWriter.newLine();
        } catch (Exception e) {
            log.info("记录测试日志异常：{}", e.getMessage());
        } finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    log.info("测试：关闭【bufferedWriter】流失败：{}", e.getMessage());
                }
            }
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    log.info("测试：关闭【fileWriter】流失败：{}", e.getMessage());
                }
            }

        }

    }
}
